package com.aidex.admin.controller.system;

import com.aidex.common.annotation.Log;
import com.aidex.common.core.controller.BaseController;
import com.aidex.common.core.domain.R;
import com.aidex.common.core.domain.entity.SysRole;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.core.domain.model.LoginUser;
import com.aidex.common.enums.BusinessType;
import com.aidex.common.query.QueryGenerator;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.poi.ExcelUtil;
import com.aidex.system.domain.SysPortalConfig;
import com.aidex.system.service.SysPortalConfigService;
import com.aidex.system.service.SysRoleService;
import com.aidex.system.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 多栏目门户配置
 */
@RestController
@RequestMapping("/system/sysPortalConfig")
public class SysPortalConfigController extends BaseController<SysPortalConfigService> {
    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysUserService userService;

    //目前写死作为系统标识
    private static String systemDefinedId = "app1";

    /**
     * 查询多栏目门户配置列表
     */
    @PreAuthorize("@ss.hasPermi('system:sysPortalConfig:list')")
    @GetMapping("/list")
    public R page(SysPortalConfig config,
                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                  HttpServletRequest req) {
        QueryWrapper<SysPortalConfig> queryWrapper = QueryGenerator.initQueryWrapper(config, req.getParameterMap());
        Page<SysPortalConfig> page = new Page<>(pageNo, pageSize);
        IPage<SysPortalConfig> pageList = service.selectPage(page, queryWrapper);
        return R.data(pageList);
    }

    /**
     * 获取多栏目门户配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:sysPortalConfig:query')")
    @GetMapping(value = "/{id}")
    public R detail(@PathVariable("id") String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>(2);
        List<SysRole> roles = roleService.selectList(new QueryWrapper<>());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        resultMap.put("roles" , SysUser.isAdmin(loginUser.getUser().getId()) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        if (StringUtils.isNotBlank(id) && !"undefined".equals(id)) {
            SysPortalConfig portalConfig = service.selectById(id);
            resultMap.put("data" , portalConfig);
            if ("U".equals(portalConfig.getApplicationRange())) {
                QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
                wrapper.in("id", portalConfig.getResourceId());
                resultMap.put("listMap" , userService.selectList(wrapper));
            }
        }
        return R.data(resultMap);
    }

    /**
     * 新增多栏目门户配置
     */
    @Log(title = "多栏目门户配置" , businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody @Validated SysPortalConfig sysPortalConfig) {
        sysPortalConfig.setSystemDefinedId(systemDefinedId);
        sysPortalConfig.setStatus("0");
//        service.insertOrUpdateSysPortalConfig(sysPortalConfig);
        return R.data(sysPortalConfig);
    }

    /**
     * 修改多栏目门户配置
     */
    @Log(title = "多栏目门户配置" , businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@RequestBody @Validated SysPortalConfig sysPortalConfig) {
//        service.insertOrUpdateSysPortalConfig(sysPortalConfig);
        return R.data(sysPortalConfig);
    }

    /**
     * 删除多栏目门户配置
     */
    @Log(title = "多栏目门户配置" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable String[] ids) {
        return R.status(service.deleteBatchIds(Arrays.asList(ids)));
    }

    /**
     * 获取最大编号
     */
    @PreAuthorize("@ss.hasPermi('system:sysPortalConfig:query')")
    @GetMapping("/findMaxSort")
    public R findMaxSort() {
        return R.data(1);
    }

    /**
     * 校验小页编码的唯一性
     */
    @PreAuthorize("@ss.hasPermi('system:sysPortalConfig:query')")
    @Log(title = "多栏目门户配置" , businessType = BusinessType.CHECK)
    @GetMapping(value = {"/checkCodeUnique/{code}/{id}" , "/checkCodeUnique/{code}"})
    public R checkCodeUnique(@NotBlank(message = "小页编码不允许为空") @PathVariable("code") String code, @PathVariable(value = "id" , required = false) String id) {
        SysPortalConfig sysPortalConfig = new SysPortalConfig();
        sysPortalConfig.setCode(code);
        sysPortalConfig.setId(id);
//        service.checkCodeUnique(sysPortalConfig);
        return R.status(Boolean.TRUE);
    }

    /**
     * 导出多栏目门户配置列表
     */
    @PreAuthorize("@ss.hasPermi('system:sysPortalConfig:export')")
    @Log(title = "多栏目门户配置" , businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public R export(SysPortalConfig config,
                    HttpServletRequest req) {
        QueryWrapper<SysPortalConfig> queryWrapper = QueryGenerator.initQueryWrapper(config, req.getParameterMap());
        List<SysPortalConfig> list = service.selectList(queryWrapper);
        ExcelUtil<SysPortalConfig> util = new ExcelUtil<SysPortalConfig>(SysPortalConfig.class);
        return util.exportExcel(list, "sysPortalConfig");
    }

    /**
     * 获取多栏目门户配置详细信息
     */
    @GetMapping("/getConfigAndPortalList/{id}")
    public R getConfigAndPortalList(@PathVariable(value = "id" , required = false) String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>(2);
//        List<SysPortlet> sysPortletList = sysPortletService.getPortletListByAuth(id);
//        resultMap.put("data" , service.selectById(id));
//        resultMap.put("sysPortletList" , sysPortletList);
        return R.data(resultMap);
    }

    @GetMapping("/getConfiglListByLoginUser")
    public R getConfiglListByLoginUser(HttpServletRequest request, HttpServletResponse response) {
//        LoginUser loginUser = SecurityUtils.getLoginUser();
//        Map<String, Object> resultMap = service.findUserConfigList(loginUser.getUser());
//        List<SysPortalConfig> userPortalConfig = null;
//        if (resultMap != null) {
//            userPortalConfig = (List<SysPortalConfig>) resultMap.get("portalList");
//        }
        return R.success();
    }

    @Log(title = "多栏目门户配置" , businessType = BusinessType.UPDATE)
    @PutMapping("/updateDefaultPortalConfig")
    public R updateDefaultPortalConfig(@RequestBody @Validated SysPortalConfig sysPortalConfig) {
//        service.updateDefaultPortalConfig(sysPortalConfig);
        return R.data(sysPortalConfig);
    }

    /**
     * 获取模板列表
     */
    @GetMapping("/getPortalTemplateList")
    public R getPortalTemplateList(HttpServletRequest request, HttpServletResponse response) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
//        List<SysPortalConfig> sysPortalConfigList = service.getPortalTemplateList(loginUser.getUser());
        return R.success();
    }


}
